package com.d3works.apps.account.db.repo;

import com.d3works.apps.account.db.PaymentSession;
import com.d3works.apps.account.exception.AccountExceptionMessage;
import com.d3works.apps.account.service.PaymentSessionService;
import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.repo.SequenceRepository;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.auth.AuthUtils;
import com.d3works.common.StringUtils;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.google.inject.Inject;
import java.math.BigDecimal;
import javax.persistence.PersistenceException;

public class PaymentSessionAccountRepository extends PaymentSessionRepository {

  @Inject PaymentSessionService paymentSessionService;
  @Inject SequenceService sequenceService;
  @Inject AppBaseService appBaseService;

  @Override
  public PaymentSession save(PaymentSession paymentSession) {
    try {
      paymentSession.setName(paymentSessionService.computeName(paymentSession));
      if (StringUtils.isEmpty(paymentSession.getSequence())) {
        paymentSession.setSequence(getSequence(paymentSession));
      }
      return super.save(paymentSession);
    } catch (Exception e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e);
    }
  }

  protected String getSequence(PaymentSession paymentSession) throws D3worksException {
    Company company = paymentSession.getCompany();
    String seq =
        sequenceService.getSequenceNumber(
            SequenceRepository.PAYMENT_SESSION, company, PaymentSession.class, "sequence");
    if (seq == null) {
      throw new D3worksException(
          TraceBackRepository.CATEGORY_CONFIGURATION_ERROR,
          I18n.get(AccountExceptionMessage.PAYMENT_SESSION_NO_SEQ),
          company.getName());
    }
    return seq;
  }

  @Override
  public PaymentSession copy(PaymentSession entity, boolean deep) {

    PaymentSession copy = super.copy(entity, deep);
    copy.setPaymentDate(appBaseService.getTodayDate(copy.getCompany()));
    copy.setAssignedToUser(AuthUtils.getUser());
    copy.setSessionTotalAmount(BigDecimal.ZERO);
    copy.setHasEmailsSent(false);
    copy.setStatusSelect(PaymentSessionRepository.STATUS_ONGOING);
    copy.setValidatedByUser(null);
    copy.setValidatedDate(null);
    copy.setName(null);
    copy.setSequence(null);
    return copy;
  }
}
